package net.tngou.crawler.company;

import java.time.Duration;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.configuration2.Configuration;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.sun.scenario.effect.impl.prism.PrImage;

import net.tngou.crawler.jdbc.DBManager;
import net.tngou.crawler.jdbc.OrderType;
import net.tngou.crawler.pojo.Area;
import net.tngou.crawler.pojo.Company;
import net.tngou.crawler.pojo.Latlng;
import net.tngou.crawler.pojo.POJO;
import net.tngou.crawler.pojo.Qichacha;

import net.tngou.crawler.util.ConfigurationUtil;
import net.tngou.crawler.util.DateUtil;
import net.tngou.crawler.util.ImgUtil;

public class QichachaUtil {

	private static HttpUtil httputil = new HttpUtil();
	
	public boolean getName(String name) {
		String url="https://www.qichacha.com/map_searchKey";
		HttpUtil httputil = new HttpUtil();
		Map<String, String> data= new HashMap<>();
		data.put("searchKey", name);
		data.put("province", "");
		data.put("city", "");
		String str = httputil.getString(url, data);
		if(StringUtils.isEmpty(str)) return true;
		str=StringUtils.remove(str, "<em>");
		str=StringUtils.remove(str, "<\\/em>");
		JSONObject json= JSON.parseObject(str);
		System.err.println(json);
		if(json.getIntValue("Status")==200)
		{
			
			JSONArray results = json.getJSONArray("Result");
			if(results==null) return true;
			for (Object object : results) {
				Qichacha bean = new Qichacha();
				JSONObject j = (JSONObject) object;
				if(name.equals(j.getString("Name"))){
					POJO pojo=bean.get("keyno='"+j.getString("KeyNo")+"'");
					if (pojo==null) {
						bean.setJson(j.toJSONString());
						bean.setKeyno(j.getString("KeyNo"));
						bean.setName(j.getString("Name"));
						bean.save();
						
						
					}
					
				};
			}
			return true;
		}else
		{
			return false;
		}
		
		
	}
	/**
	 * 通过坐标找企业
	 */
	
	public static  int searchByLocation(int page,double distance,LocalDate startDate,LocalDate endDate,double lat, double lng) {
		System.err.println(startDate+"~"+endDate+":"+page);
		try {
			Thread.sleep(1000*3);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		int size=0;
		String url="https://www.qichacha.com/map_searchByLocation";
		Map<String, String> data=new HashMap<>();
		data.put("distance",distance+"");
		data.put("industryCode","");//行业分类
		data.put("subIndustryCode","0");
		data.put("latitude",lat+"");
		data.put("longitude",lng+"");
		data.put("pageIndex",page+"");
		data.put("pageSize","10");
		data.put("registCapiBegin","");	
		data.put("registCapiEnd","");//注册资金
		data.put("searchKey","");	
		data.put("searchType","multiple");	
		data.put("startDateBegin",DateUtil.format(startDate, "yyyyMMdd"));	//注册开始时间
		data.put("startDateEnd",DateUtil.format(endDate, "yyyyMMdd"));	//注册结束时间
		data.put("statusCode","");	
		data.put("isSortAsc","");
		data.put("sortField","");
		String str =httputil.postString(url, data);
//		System.err.println(str);
		if(StringUtils.isNotEmpty(str))
		{
			JSONObject json= JSON.parseObject(str);
			int listCount = json.getIntValue("listCount");
			System.err.println("数据总数："+listCount);
			if(listCount!=0)
			{
				JSONArray array = json.getJSONArray("list");
				//写入数据
				System.err.println("写入数据:"+array.size());
				array.forEach(e->{
					JSONObject j=(JSONObject) e;						
					System.err.println(j.getString("Name"));
//					System.err.println(j.getString("KeyNo"));
					Qichacha bean = new Qichacha();
					POJO pojo=bean.get("keyno='"+j.getString("KeyNo")+"'");
					if (pojo==null) {
						bean.setJson(j.toJSONString());
						bean.setKeyno(j.getString("KeyNo"));
						bean.setName(j.getString("Name"));
						bean.save();
					}
				});
				if(listCount>=100&&page==1) {	
					LocalDate[][] obs=split(startDate, endDate);
					size=size+searchByLocation(page,distance, obs[0][0], obs[0][1], lat, lng);
					size=size+searchByLocation(page,distance, obs[1][0], obs[1][1], lat, lng);
				}else
				{
					if (page==1) {
						int p=listCount/10+1;
						for (int i = 2; i < p; i++) {
							searchByLocation(i, distance, startDate, endDate, lat, lng);
						}
					}
					size=size+listCount;
					
				}

			}else
			{
				System.err.println(json);
				
			}
			
		}else
		{
			System.err.println("错误");
			return Integer.MIN_VALUE;
		}
		return size;
		
	}
	
	public static int saveCompay(double distance,double lat,double lng) {
		int size=0;
		int years=100; //60年
		LocalDate now =LocalDate.now();
		LocalDate endDate=now.minusYears(0);
		LocalDate startDate=now.minusYears(100);
//		for (int i = 0; i <=years; ) {
//			LocalDate endDate=now.minusYears(i);
//			i=i+5;
//			LocalDate startDate=now.minusYears(i);
//			if((i-5)==years)
//				startDate=now.minusYears(i+40);
//			
//			size=size+searchByLocation(distance, startDate,endDate,lat, lng);
//			
//		}
		
		size=size+searchByLocation(1,distance, startDate,endDate,lat, lng);
		return size;
		
	}
	
	/**
	 * 分割时间
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static  LocalDate[][] split(LocalDate startDate,LocalDate endDate) {
		Duration dur=DateUtil.between(startDate, endDate);
		long size = dur.toDays()/2;
		LocalDate[][] obs= new LocalDate[2][2];
		obs[0][0]=startDate;
		obs[0][1]=startDate.plusDays(size);
		obs[1][0]=startDate.plusDays(size);
		obs[1][1]=endDate;

		return obs;
	}
	
	public static Company change(Qichacha qichacha) {
		String str = qichacha.getJson();
		JSONObject json = JSON.parseObject(str);
		Company company= new Company();
		company.setName(json.getString("Name"));
		company.setNo(json.getString("No"));
		company.setProvince(json.getString("Province"));
		company.setRegist_org(json.getString("BelongOrg"));
		company.setRegist_org_no(json.getString("OrgNo"));
		company.setCredit_code(json.getString("CreditCode"));
		company.setEconkind(json.getString("EconKind"));
		company.setRegist_date(json.getString("StartDate"));
		company.setExpired(json.getString("IsExpired"));
		company.setAddress(json.getString("Address"));
		company.setLat(json.getDoubleValue("X"));
		company.setLng(json.getDoubleValue("Y"));
		JSONObject industry = json.getJSONObject("Industry");
		if(industry!=null) {
			company.setIndustry(industry.getString("Industry"));
			company.setSubIndustry(industry.getString("SubIndustry"));
		}
		company.setRegist_capi(json.getString("RegistCapi"));
		company.setStatus(json.getString("Status"));
		company.setShort_status(json.getString("ShortStatus"));
		company.setOper_name(json.getString("OperName"));
		company.setEnglish_name(json.getString("EnglishName"));
		company.setWeb_site(json.getString("WebSite"));
		company.setTel(json.getString("ContactNumber"));
		company.setEmail(json.getString("Email"));
		company.setTag(json.getString("Tag"));
		company.setScope(json.getString("Scope"));
		company.setFinancing(json.getString("Financing"));
		String imageUrl = json.getString("ImageUrl");
		if(StringUtils.isNoneEmpty("imageUrl")&&imageUrl.indexOf("default.jpg")<0)
		{
			Configuration config = ConfigurationUtil.config("info");
			String savePath=config.getString("savePath");
			String saveUrl=config.getString("saveUrl");
			String imgurl = ImgUtil.DownImg(imageUrl, savePath, saveUrl);
			company.setLogo(imgurl);
		}
		company.setKeyno(json.getString("KeyNo"));
		return company;
		
	}
	
	public static void main(String[] args) {
//		System.err.println(Integer.MIN_VALUE);
		Latlng bean = new Latlng();
		while (true) {
			List<Latlng > list = (List<Latlng>) bean.list("state=2",1, 100, "id", OrderType.DESC);
			if(list==null||list.size()==0) break;
			for (Latlng latlng : list) {
				int size=saveCompay(10,latlng.getLat(),latlng.getLng());		
//				System.err.println(size);
				if(size>=0) {
					latlng.setState(3);
					latlng.setSize(size);
					latlng.update();
				}
				DBManager.closeConnection();//回收连接
			}
		}
	}
	
}
